﻿using Sodu.Entity;
using Sodu.UC;
using Sodu.Util;
using Sodu.Util.HttpHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace Sodu.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class Page_SearchResult : Page
    {

        /// <summary>
        /// 普通的列表
        /// </summary>
        public List<BookEntity> BookEntityList;

        SearchParameterEntity Entity;

        int PrePage = 1;
        int NextPage = 1;
        int LastPage = 1;

        /// <summary>
        /// 搜索条件
        /// </summary>
        private string SearchPara = string.Empty;

        /// <summary>
        /// 当前页码
        /// </summary>
        private int PageIndex = 0;

        public Page_SearchResult()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Disabled;

            SetButtonVisibility();
        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。
        /// 此参数通常用于配置页。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ///重写返回键事件
            Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;

            if (e.Parameter != null)
            {
                SearchParameterEntity t_entity = (SearchParameterEntity)e.Parameter;

                SearchPara = t_entity.SearchParameter;
                this.txtSearch.Text = SearchPara;

                PageIndex = t_entity.PageNumber;

                GetSearchtData((SearchParameterEntity)e.Parameter);


            }
        }


        /// <summary>
        /// 获取数据,并赋值
        /// </summary>
        /// <param name="html"></param>
        public void GetSearchtData(SearchParameterEntity entity)
        {
            SetControlVisibilaty(1);
            string uri = string.Format(SoduConstants.SoduContantsValue.BookSearchPage, ChineseGBKConverter.Utf8ToGb2312(entity.SearchParameter), entity.PageNumber);
            HttpHelper.HttpGetRequest(uri, GetDataCompleted);
        }



        /// <summary>
        /// 获取数据结束
        /// </summary>
        /// <param name="html"></param>
        async public void GetDataCompleted(string html)
        {
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                try
                {
                    if (string.IsNullOrEmpty(html))
                    {
                        throw new Exception();
                    }
                    else
                    {
                        SetData(html);
                    }
                }
                catch (Exception ex)
                {
                    Exceptionhandle();

                }
            }
                 );
        }

        /// <summary>
        /// 当获取数据异常时调用
        /// </summary>
        public void Exceptionhandle()
        {
            BookEntity t_entity = new BookEntity() { BookName = "网络错误", ChapterName = "暂无数据" };
            UC_BookListItem t_item = new UC_BookListItem(t_entity);
            t_item.IsEnabled = false;
            this.pnlButton.Visibility = Visibility.Collapsed;
            this.pnlSearchResult.Children.Add(t_item);
            MessageBox.Show("获取数据失败，请重试。");
        }

        /// <summary>
        /// 为界面赋值
        /// </summary>
        /// <param name="html"></param>
        public void SetData(string html)
        {
            try
            {
                this.pnlSearchResult.Children.Clear();

                BookEntityList = GetBookEntitykList.GetBookEntitykListFromHtml(html);

                GetBookEntitykList.GetSearchPageIndexFromHtml(html, out PrePage, out NextPage, out LastPage);


                if (BookEntityList != null && BookEntityList.Count > 0)
                {
                    UC_BookListItem t_item;
                    for (int i = 0; i < BookEntityList.Count; i++)
                    {
                        t_item = new UC_BookListItem(BookEntityList[i]);
                        this.pnlSearchResult.Children.Add(t_item);
                    }
                }
                else
                {
                    BookEntity t_entity = new BookEntity() { BookName = "搜索结果为空", ChapterName = "暂无数据" };
                    UC_BookListItem t_item = new UC_BookListItem(t_entity);
                    t_item.IsEnabled = false;
                    this.pnlButton.Visibility = Visibility.Collapsed;
                    this.pnlSearchResult.Children.Add(t_item);
                }

                this.txtPageIndex.Text = PageIndex.ToString();
                this.txtPageCount.Text = LastPage.ToString();
            }

            catch (Exception ex)
            {
                Exceptionhandle();
            }
            finally
            {
                SetControlVisibilaty(2);
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrePage_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_SearchResult), new SearchParameterEntity(SearchPara, PrePage));
        }
        /// <summary>
        /// 下页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_SearchResult), new SearchParameterEntity(SearchPara, NextPage));
        }

        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLastPage_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_SearchResult), new SearchParameterEntity(SearchPara, LastPage));
        }


        private void DisableBtn()
        {
            ///就一页
            if (LastPage == 1)
            {
                this.btnLastPage.IsEnabled = false;
                this.btnPrePage.IsEnabled = false;
                this.btnNextPage.IsEnabled = false;
            }
            else if (NextPage == 2 && NextPage != LastPage)
            {
                this.btnLastPage.IsEnabled = true;
                this.btnPrePage.IsEnabled = false;
                this.btnNextPage.IsEnabled = true;
            }
            else if (LastPage == NextPage && LastPage == PageIndex)
            {
                this.btnLastPage.IsEnabled = false;
                this.btnPrePage.IsEnabled = true;
                this.btnNextPage.IsEnabled = false;
            }
            else
            {
                this.btnLastPage.IsEnabled = true;
                this.btnPrePage.IsEnabled = true;
                this.btnNextPage.IsEnabled = true;
            }

        }

        #region  公共方法

        public void SetButtonVisibility()
        {

            if (SoduConstants.SoduContantsValue.IfLogin == true)
            {
                this.pnlLoaded.Visibility = Visibility.Visible;
                this.pnlUnLoad.Visibility = Visibility.Collapsed;
                this.btnUser.Content = SoduConstants.SoduContantsValue.UserName;
            }
            else
            {
                this.pnlLoaded.Visibility = Visibility.Collapsed;
                this.pnlUnLoad.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// 离开时取消返回事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
        }

        async private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
        {
            e.Handled = true;
            if (!Frame.CanGoBack)
            {
                var dig = new MessageDialog("确定要退出Sodu?", "确认");
                var btnOk = new UICommand("是");
                dig.Commands.Add(btnOk);
                var btnCancel = new UICommand("否");
                dig.Commands.Add(btnCancel);

                var result = await dig.ShowAsync();
                if (null != result && result.Label == "是")
                {
                    Application.Current.Exit();
                }
            }
            else
            {
                Frame.GoBack();
            }
        }

        /// <summary>
        ///   1 加载中  2 加载完成
        /// </summary>
        /// <param name="flag"></param>
        public void SetControlVisibilaty(int flag = -1)
        {

            ///加载中
            if (flag == 1)
            {
                this.progress.Visibility = Visibility.Visible;
                this.pnlContent.Visibility = Visibility.Collapsed;
            }

            //加载完成 
            else if (flag == 2)
            {
                this.progress.Visibility = Visibility.Collapsed;
                this.pnlContent.Visibility = Visibility.Visible;
            }

            DisableBtn();
        }

        /// 点击回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Page_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                if (FocusManager.GetFocusedElement() == this.txtSearchPara)
                {
                    btnSearch_Click(null, null);
                }
            }
        }

        /// <summary>
        /// 点击搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtSearchPara.Text))
            {
                MessageBox.Show("请输入搜索关键字");
                return;
            }
            Frame.Navigate(typeof(Page_SearchResult), new SearchParameterEntity(ChineseGBKConverter.ConvertChinestStringtoGBKString(this.txtSearchPara.Text), 1));
        }

        /// <summary>
        /// 点击排行榜
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRankList_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_RankList), 1);
        }

        /// <summary>
        /// 点击登录按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_Login));
        }

        /// <summary>
        /// 点击注册按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_Register));
        }


        /// <summary>
        /// 点击注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogout_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(MainPage), "logout");
        }

        /// <summary>
        /// 点击用户名进入书架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUser_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_BookShelf));
        }

        /// <summary>
        /// 点击图片logo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            if (SoduConstants.SoduContantsValue.IfLogin)
            {
                Frame.Navigate(typeof(Page_Loaded));

            }
            else
            {
                Frame.Navigate(typeof(MainPage));
            }
        }

        #endregion





    }


    public class SearchParameterEntity
    {
        /// <summary>
        /// 索引页
        /// </summary>
        public int PageNumber { get; set; }

        /// <summary>
        /// 搜索参数
        /// </summary>
        public string SearchParameter { get; set; }


        public SearchParameterEntity(string para, int pageIndex)
        {
            this.SearchParameter = para;
            this.PageNumber = pageIndex;
        }
    }
}
